package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.order.client.OrderInfoClientFeign;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.user.client.UserClientFeign;
import com.atguigu.tingshu.vo.album.AlbumTrackListVo;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackStatVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

    @Autowired
    private TrackInfoMapper trackInfoMapper;

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Autowired
    private VodService vodService;

    @Autowired
    private TrackStatMapper trackStatMapper;

    @Autowired
    private AlbumInfoMapper albumInfoMapper;

    @Autowired
    private UserClientFeign userClientFeign;

    @Autowired
    private OrderInfoClientFeign orderInfoClientFeign;



    /**
     * 保存声音
     * @param trackInfoVo
     */
    @Override
    public void saveTrackInfo(TrackInfoVo trackInfoVo) {
        //声明实体类对象,用于保存数据
        TrackInfo trackInfo = new TrackInfo();
        //将trackInfoVo的数据赋值到trackInfo
        BeanUtils.copyProperties(trackInfoVo, trackInfo);
        //补齐其他信息
        //获取用户id
        Long userId = AuthContextHolder.getUserId();

        //通过云点播获取到具体文件的唯一id
        MediaInfo mediaInfo = vodService.getTrackDetailInfo(trackInfoVo.getMediaFileId());
        //
        MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
        //获取文件类型
        String type = basicInfo.getType();
        //获取文件播放地址
        String mediaUrl = basicInfo.getMediaUrl();
        trackInfo.setMediaUrl(mediaUrl);
        //获取coverUrl
        String coverUrl = basicInfo.getCoverUrl();
        trackInfo.setCoverUrl(coverUrl);
        //获取声音时长
        Float duration = mediaInfo.getMetaData().getDuration();
        trackInfo.setMediaDuration(new BigDecimal(duration));
        //获取声音大小
        Long size = mediaInfo.getMetaData().getSize();
        trackInfo.setMediaSize(size);
        //查询数据库中当前这个专辑的声音的order_num的最大值到几了
        Integer orderNum =
                trackInfoMapper.selectTrackMaxOrderNum(trackInfoVo.getAlbumId());
        if(orderNum == null){
            orderNum = 0;
        }else {
            trackInfo.setOrderNum(orderNum + 1);
        }
        //保存用户id
        trackInfo.setUserId(userId);
        trackInfoMapper.insert(trackInfo);

        //保存统计信息
        TrackStat trackStat = new TrackStat();


        //保存播放量
        trackStat.setTrackId(trackInfo.getId());
        trackStat.setStatType(SystemConstant.TRACK_STAT_PLAY);
        trackStat.setStatNum(0);
        trackStatMapper.insert(trackStat);



        //保存收藏量
        TrackStat trackStat2 = new TrackStat();

        //保存播放量
        trackStat2.setTrackId(trackInfo.getId());
        trackStat2.setStatType(SystemConstant.TRACK_STAT_PLAY);
        trackStat2.setStatNum(0);
        trackStat2.setStatType(SystemConstant.TRACK_STAT_COLLECT);
//        trackStat.setStatNum(0);
        trackStatMapper.insert(trackStat2);


        //保存点赞
        trackStat.setTrackId(null);
        trackStat.setStatType(SystemConstant.TRACK_STAT_PRAISE);
//        trackStat.setStatNum(0);
        trackStatMapper.insert(trackStat);
        //评论
        trackStat.setTrackId(null);
        trackStat.setStatType(SystemConstant.TRACK_STAT_COMMENT);
//        trackStat.setStatNum(0);
        trackStatMapper.insert(trackStat);

        //查询专辑信息
        AlbumInfo albumInfo =
                albumInfoMapper.selectById(trackInfoVo.getAlbumId());
        if (albumInfo != null) {
            //声音数量+1
            albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() + 1);
        }
        albumInfoMapper.updateById(albumInfo);
    }


    /**
     * 删除声音
     * @param trackId
     */
    @Override
    public void removeTrackInfo(Integer trackId) {


        LambdaQueryWrapper<TrackInfo> wrapper = new LambdaQueryWrapper<TrackInfo>()
                //验证用户
                .eq(TrackInfo::getUserId,AuthContextHolder.getUserId())
                //删除哪张专辑的声音
                .eq(TrackInfo::getId,trackId);
        //获取声音详细信息
        TrackInfo trackInfo = getBaseMapper().selectOne(wrapper);
        //如果为空，则声音为空
        if (trackInfo ==null){
            throw new GuiguException(201,"声音不存在");
        }//否则就删除
       removeById(trackId);
        //删除统计表
        trackStatMapper.delete(new LambdaQueryWrapper<TrackStat>()
                .eq(TrackStat::getTrackId,trackId));
        //根据专辑id获取到具体的声音信息
        AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfo.getAlbumId());
        //专辑的声音减一
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount()-1);
        //根据文件唯一标识id，删除云点播的文件
        vodService.removeFile(trackInfo.getMediaFileId());


    }

    /**
     * 声音列表分页
     * @param trackInfoQuery
     * @param pageInfo
     * @return
     */
    @Override
    public Page<TrackListVo> findUserTrackPage(TrackInfoQuery trackInfoQuery, Page<TrackListVo> pageInfo) {
        Long userId = AuthContextHolder.getUserId();
        return trackInfoMapper.findUserTrackPage(trackInfoQuery,pageInfo,userId);
    }

    /**
     * 修改声音
     * @param trackInfoVo
     * @param trackId
     */
    @Override
    public void updateTrackInfo(TrackInfoVo trackInfoVo, Long trackId) {
        //获取声音数据
        TrackInfo trackInfo = trackInfoMapper.selectOne(new LambdaQueryWrapper<TrackInfo>()
                .eq(TrackInfo::getUserId,AuthContextHolder.getUserId())
                .eq(TrackInfo::getId,trackId));
        if (trackInfo==null){
            throw new GuiguException(201,"声音不存在");
        }
        //获取修改前文件id
        String oldmediaFileId = trackInfo.getMediaFileId();
        //获取本次修改的文件id
        String newmediaFileId = trackInfoVo.getMediaFileId();
        //属性替换
        BeanUtils.copyProperties(trackInfoVo,trackInfo);
        //判断声音文件是否变化
        if (oldmediaFileId.equals(newmediaFileId)){
            //有变化的，删除
            vodService.removeFile(oldmediaFileId);

            //查询新的信息
            MediaInfo mediaInfo = vodService.getTrackDetailInfo(newmediaFileId);
            //使用新的信息替换旧的信息，大小，时长，播放地址，类型
            MediaMetaData metaData = mediaInfo.getMetaData();
            //时长
            trackInfo.setMediaDuration(new BigDecimal(metaData.getDuration()));
            //大小
            trackInfo.setMediaSize(metaData.getSize());
            MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
            //播放地址
            trackInfo.setMediaUrl(basicInfo.getMediaUrl());
            trackInfo.setMediaType(basicInfo.getType());
            //修改声音
            updateById(trackInfo);
        }
    }
    @Override
    public List<AlbumTrackListVo>  findAlbumTrackPage(Page<AlbumTrackListVo> trackInfoIPage, Long albumId) {
        //根据专辑id获取专辑数据
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        //获取用户id
        Long userId = AuthContextHolder.getUserId();
        List<AlbumTrackListVo> result = trackInfoMapper.getAlbumTrackListVo(trackInfoIPage,albumId);
        trackInfoIPage.setRecords(result);
        //付费类型: 0101-免费、0102-vip免费、0103-付费
        //获取该专辑的付费类型//付费类型: 0101-免费、0102-vip免费、0103-付费
        switch ( albumInfo.getPayType()){
            //免费专辑
            case "0101" -> {
                //免费就直接全部返回
                    return result;
            }
            //vip免费
            case "0102" -> {
                //判断用户vip身份
                //获取用户vip过期时间
                Long vipExpireTime = AuthContextHolder.getvipExpireTime();
                long nowTime = System.currentTimeMillis();
                //如果VIP时间不为空而且大于现在的时间，说明vip身份没过期
                if (vipExpireTime != null && vipExpireTime > nowTime){
                    //将专辑全部免费展示
                    return result;
                }
                else {
                    //设置免费试听集数
                    albumInfo.setTracksForFree(5);
                    albumInfoMapper.updateById(albumInfo);
                    //不是vip，将专辑设置为付费
                    //将专辑收费便签显示
                    result.forEach(albumTrackListVo -> {
                        //获取专辑声音数量
                        Integer orderNum = albumTrackListVo.getOrderNum();
                        //如果声音数量大于试听集数
                        if (orderNum>albumInfo.getTracksForFree()){
                            //就把收费标签显示
                            albumTrackListVo.setIsShowPaidMark(true);
                        }
                    });
                    return result;
                }
            }
            //付费专辑
            case "0103" -> {
                //购买整张专辑
                UserPaidAlbum userPaidAlbum = userClientFeign.BuyAlbum(userId, albumId);
                //如果购买记录不为空
                if (userPaidAlbum != null){
                    result.forEach(albumTrackListVo -> {
                        //获取专辑声音数量
                        Integer orderNum = albumTrackListVo.getOrderNum();
                        //如果声音数量大于试听集数
                            //就把收费标签显示
                            albumTrackListVo.setIsShowPaidMark(true);
                    });
                    //返回专辑全部数据
                    return result;
                }
                //购买单个声音
                //获取用户购买的声音id
                List<Long> buytrack = userClientFeign.buytrack(userId, albumId);
                //获取免费试听集数
                Integer tracksForFree = albumInfo.getTracksForFree();

                result.stream().forEach( albumTrackListVo -> {
                    Integer orderNum = albumTrackListVo.getOrderNum();
                    //如果声音数量大于试听集数
                    if (orderNum>albumInfo.getTracksForFree()){
                        //就把收费标签显示
//                        albumTrackListVo.setIsShowPaidMark(true);
                        albumTrackListVo.setIsShowPaidMark(!buytrack.contains(albumTrackListVo.getTrackId()));
                    }
                });
                return result;
            }
        }
        //会员免费专辑
        return null;
    }

    /**
     * 获取声音进度
     * @param trackId
     * @return
     */
    @Override
    public Object getTrackStatVo(Long trackId) {
        TrackStatVo trackInfoVo =  new TrackStatVo();
        //获取统计信息
        Map<String, Integer> collect = trackStatMapper.selectList(new LambdaQueryWrapper<TrackStat>().eq(TrackStat::getTrackId, trackId)).stream().collect(Collectors.toMap(
                        key -> key.getStatType(),
                        value -> value.getStatNum()
                )
        );
        //赋值
        trackInfoVo.setPlayStatNum(collect.get(SystemConstant.TRACK_STAT_PLAY));
        trackInfoVo.setCollectStatNum(collect.get(SystemConstant.TRACK_STAT_COLLECT));
        trackInfoVo.setPraiseStatNum(collect.get(SystemConstant.TRACK_STAT_PRAISE));
        trackInfoVo.setCommentStatNum(collect.get(SystemConstant.TRACK_STAT_COMMENT));
        //返回
        return trackInfoVo;
    }

    /**
     * 查询用户购买声音列表
     * @param trackId
     * @return
     */
    @Override
    public Object findUserTrackPaidList(Long trackId) {
        //查询当前声音信息
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
        //获取专辑id
        Long albumId = trackInfo.getAlbumId();
        //获取当前声音的专辑 的声音列表
        List<AlbumInfo> albumInfoList = albumInfoMapper.selectList(new LambdaQueryWrapper<AlbumInfo>().eq(AlbumInfo::getId, trackInfo.getAlbumId()));
        //获取用户买过的声音列表->从用户微服务获取
        List<Long> buytrack = userClientFeign.buytrack(AuthContextHolder.getUserId(), albumId);//只有trackID字段
        Map<String, Object> userTrackOrderMap =
                orderInfoClientFeign.getUserTrackOrderInfo(AuthContextHolder.getUserId());
        return null;
    }

    /**
     * 初始化声音的统计信息
     * @param trackId
     */
    private void initTrackStat(Long trackId) {
        //初始化Do
        TrackStat trackStat = new TrackStat();
        //播放量初始化
        trackStat.setTrackId(trackId);
        trackStat.setStatNum(0);
        trackStat.setStatType(SystemConstant.TRACK_STAT_PLAY);
        trackStatMapper.insert(trackStat);
        //收藏量
        trackStat.setId(null);
        trackStat.setStatType(SystemConstant.TRACK_STAT_COLLECT);
        trackStatMapper.insert(trackStat);
        //点赞量
        trackStat.setId(null);
        trackStat.setStatType(SystemConstant.TRACK_STAT_PRAISE);
        trackStatMapper.insert(trackStat);
        //评论数
        trackStat.setId(null);
        trackStat.setStatType(SystemConstant.TRACK_STAT_COMMENT);
        trackStatMapper.insert(trackStat);
    }
}




